//
//  CollectionViewController.swift
//  swift各类控件集锦
//
//  Created by iosdev1 on 2017/4/21.
//  Copyright © 2017年 zyy. All rights reserved.
//

import UIKit

class CollectionViewController: ZyBaseViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, ZyyCollectionViewCellDelegate {

    var colltionView:UICollectionView! = nil
    var arrData:Array<String>!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        arrData = ["0","1","2","3","4","5","6","7","8","9","10"]
        
        let layout = UICollectionViewFlowLayout.init()
        layout.scrollDirection = UICollectionViewScrollDirection.vertical
        
        colltionView = UICollectionView.init(frame: CGRect(x:0, y:0, width:WIDTH_SCREEN, height:HEIGHT_SCREEN), collectionViewLayout: layout)
        
        colltionView.delegate = self
        colltionView.dataSource = self
        colltionView.backgroundColor = UIColor.yellow
        self.view.addSubview(colltionView)
        
       // MARK:   //注册一个cell
        colltionView.register(ZyyCollectionViewCell.self, forCellWithReuseIdentifier: "cellId")
        
        colltionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headView")
        colltionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "footView")
        
//        菜单栏 复制 粘贴 等
        let menuItem = UIMenuItem.init(title: "Custom Action", action: #selector(customAction(sender:)))
        let menuItem1 = UIMenuItem.init(title: "zyy自定义1", action: #selector(menuItemFunc1(sender:)))
        let menuItem2 = UIMenuItem.init(title: "zyy自定义2", action: #selector(menuItemFunc2(sender:)))
        let menuItem3 = UIMenuItem.init(title: "zyy自定义3", action: #selector(menuItemFunc3(sender:)))
        let menuItem4 = UIMenuItem.init(title: "zyy自定义4", action: #selector(menuItemFunc4(sender:)))
        
        UIMenuController.shared.menuItems = NSArray.init(objects: menuItem, menuItem1,menuItem2, menuItem3, menuItem4) as? [UIMenuItem]
    }
    
// MARK:    UICollectionViewDelegate的代理方法
    func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
//        zyUIshowMessage(message: "管理cell的高亮")
        return true
    }
    
    func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
//        zyUIshowMessage(message: "管理cell的高亮")
    }
    
    func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
//        zyUIshowMessage(message: "管理cell的高亮")
    }
    
    func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool {
       zyUIshowMessage(message: " 取消选择")
        return true
    }
    
    func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        zyUIshowMessage(message: " 管理cell的选择")
        return true
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//        zyUIshowMessage(message: "点击了item")
    }
    
//MARK://    取消选择指定的项目
    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        zyUIshowMessage(message: "已经取消选择")
    }
    
    //由于重用机制，消失在屏幕外的SupplementaryView 会重新出现在屏幕上的使用;
    //使用字典以 indexPath 为键，以对应的 SupplementaryView 为值来维护屏幕上可见的 SupplementaryView的信息。
    //在这里执行观察操作，如果该 indexPath 在字典里不存在则新建，若存在则更新该键的值。
    func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) {
        zyUIshowMessage(message: "重新出现")
    }
    
    //对消失在屏幕上的 SupplementaryView 执行解除监听操作；
    func collectionView(_ collectionView: UICollectionView, didEndDisplayingSupplementaryView view: UICollectionReusableView, forElementOfKind elementKind: String, at indexPath: IndexPath) {
        zyUIshowMessage(message: "解除监听操作")
    }

    
//     These methods provide support for copy/paste actions on cells.
//     All three should be implemented if any are.
//MARK:    显示编辑菜单（如复制，粘贴等）
    func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
        zyUIshowMessage(message: " 是否显示菜单")
        return true
    }
    
    func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
//        zyUIshowMessage(message: "//菜单中哪些编辑操作可以显示")
        if action == #selector(menuItemFunc1(sender:)) {
            return true
        }else if action == #selector(menuItemFunc2(sender:)) {
            return true
        }else if action == #selector(menuItemFunc3(sender:)) {
            return false
        }else if action == #selector(menuItemFunc4(sender:)) {
            return true
        }
        return true
    }
    
    func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
//        zyUIshowMessage(message: "//对于显示的编辑操作怎么执行")
        if action == #selector(menuItemFunc1(sender:)) {
            zyUIshowMessage(message: "performAction:menuItemFunc1")
        }else if action == #selector(menuItemFunc2(sender:)) {
            zyUIshowMessage(message: "performAction:menuItem2")
        }else if action == #selector(menuItemFunc3(sender:)) {
            zyUIshowMessage(message: "performAction:menuItem3")
        }else if action == #selector(menuItemFunc4(sender:)) {
            zyUIshowMessage(message: "performAction:menuItem4")
        }
    }
    
//     // support for custom transition layout
//MARK://    使用交互过渡改变当前布局
    func collectionView(_ collectionView: UICollectionView, transitionLayoutForOldLayout fromLayout: UICollectionViewLayout, newLayout toLayout: UICollectionViewLayout) -> UICollectionViewTransitionLayout {
        zyUIshowMessage(message: "71")
        let transLayout = UICollectionViewTransitionLayout.init(currentLayout: fromLayout, nextLayout: toLayout)
        return transLayout
    }
    
//MARK: //    ios9 以上支持
//    func collectionView(_ collectionView: UICollectionView, canFocusItemAt indexPath: IndexPath) -> Bool {
//        
//        return true
//    }
//    
//    @available(iOS 9.0, *)
//    func collectionView(_ collectionView: UICollectionView, shouldUpdateFocusIn context: UICollectionViewFocusUpdateContext) -> Bool {
//        
//        return true
//    }
//    
//    @available(iOS 9.0, *)
//    func collectionView(_ collectionView: UICollectionView, didUpdateFocusIn context: UICollectionViewFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
//        
//    }
    
//    func indexPathForPreferredFocusedView(in collectionView: UICollectionView) -> IndexPath? {
//        return IndexPath.init(item: 1, section: 1)
//    }
//    
    func collectionView(_ collectionView: UICollectionView, targetIndexPathForMoveFromItemAt originalIndexPath: IndexPath, toProposedIndexPath proposedIndexPath: IndexPath) -> IndexPath {
        let index = IndexPath.init(item: 0, section: 2)
        zyUIshowMessage(message: "81")
        return index
    }

    func collectionView(_ collectionView: UICollectionView, targetContentOffsetForProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
        let point = CGPoint(x:10, y:100)
        zyUIshowMessage(message: "91")
        return point
    }
    
//MARK: //UICollectionViewDataSource代理方法的实现
//    cell的个数（一个section里）
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return arrData.count
    }
    
    // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
//MARK: //    返回指定索引路径的cell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! ZyyCollectionViewCell    
        cell.backgroundColor = UIColor.init(colorLiteralRed: Float(arc4random()%250)/250, green: Float(arc4random()%250)/250, blue: Float(arc4random()%250)/250, alpha: Float(arc4random()%250)/250)
        cell.lblTitle.text = arrData[3]
        cell.delegate = self
        return cell
    }
    
//MARK: //    section的个数
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 5
    }
    
        // The view that is returned must be retrieved from a call to -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:
//MARK: //    设置header和footer
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionElementKindSectionHeader {
            let headView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headView", for: indexPath)
            headView.backgroundColor = UIColor.orange
            
            let lblTitle = UILabel.init(frame: CGRect(x:10, y:0, width:60, height:20))
            lblTitle.text = "headTitle"
            headView.addSubview(lblTitle)
             return headView
        }else if kind == UICollectionElementKindSectionFooter {
            let footView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "footView", for: indexPath)
            footView.backgroundColor = UIColor.green
            
            let lblTitle = UILabel.init(frame: CGRect(x:10, y:0, width:60, height:20))
            lblTitle.text = "footView"
            footView.addSubview(lblTitle)
            return footView
        }
        let headView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headView", for: indexPath)
        headView.backgroundColor = UIColor.orange
        
        let lblTitle = UILabel.init(frame: CGRect(x:10, y:0, width:60, height:20))
        lblTitle.text = "未知错误"
        headView.addSubview(lblTitle)
        return headView
    }
    
    func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
        zyUIshowMessage(message: "101")
        return true
    }
    
    func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        zyUIshowMessage(message: "111")
    }
    
        /// Returns a list of index titles to display in the index view (e.g. ["A", "B", "C" ... "Z", "#"])
    func indexTitles(for collectionView: UICollectionView) -> [String]? {
        let arrTitle = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","#"]
//        let arrTitle = ["A","B","","R","S","T","U","V","W","X"]
        zyUIshowMessage(message: "121")
        return arrTitle
    }
//
//    /// Returns the index path that corresponds to the given title / index. (e.g. "B",1)
//    /// Return an index path with a single index to indicate an entire section, instead of a specific item.
    func collectionView(_ collectionView: UICollectionView, indexPathForIndexTitle title: String, at index: Int) -> IndexPath {
        zyUIshowMessage(message: "131")
        return IndexPath.init(item: 1, section: 2)
    }
    
//    UICollectionViewDelegateFlowLayout代理方法的实现
//MARK: //    cell的大小
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        return CGSize(width: 120, height:80)
    }
    
//MARK: //    每个section的margin
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        let edges = UIEdgeInsetsMake(10, 20, 30, 40)
        return edges
    }
    
//MARK://    每个section中不同行的行间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 20
    }
    
//MARK: //    每个item的距离
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
//MARK: ////footView的大小
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize(width:100, height:40)
    }

//MARK:    //HeaderView的大小
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width:100, height:40)
    }
    
//    MARK: UIMenuController required methods
    override var canBecomeFirstResponder: Bool{
        zyUIshowMessage(message: "成为第一响应")
        return true;
    }
    
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
//        点击item的时候调用
        zyUIshowMessage(message: "点击item的时候调用")
        if action == #selector(menuItemFunc1(sender:)) {
            return true
        }else if action == #selector(menuItemFunc2(sender:)) {
            return false
        }else if action == #selector(menuItemFunc3(sender:)) {
            return false
        }else if action == #selector(menuItemFunc4(sender:)) {
            return true
        }else if action == #selector(customAction(sender:)) {
            return true
        }
        return false
    }
    
    
//    MARK: customAction
    func customAction(sender:Any) -> Void {
        print("customAction")
    }
    
    func menuItemFunc1(sender:Any) -> Void {
        print("menuItemFunc1")
    }
    
    func menuItemFunc2(sender:Any) -> Void {
        zyUIshowMessage(message: "menuItem2")
    }
    
    func menuItemFunc3(sender:Any) -> Void {
        zyUIshowMessage(message: "menuItem3")
    }
    
    func menuItemFunc4(sender:Any) -> Void {
        zyUIshowMessage(message: "menuItem4")
    }


//    MARK: 实现cell里的代理方法
    func menuItemFunc1(string: String, forString: String) {
        print("\(string)与\(forString)")
    }
    
    func menuItemFunc2(string: String, forString: String) {
        print("\(string)与\(forString)")
    }
    
    func menuItemFunc3(string: String, forString: String) {
        print("\(string)与\(forString)")
    }
    
    func menuItemFunc4(string: String, forString: String) {
        print("\(string)与\(forString)")
    }
    
    func customAction(string: String, forString: String) {
        print("\(string)与\(forString)")
    }
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
